import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

const service = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 10000
})

// 添加头像URL处理函数
export const getAvatarUrl = (avatar) => {
  if (!avatar) return '/default-avatar.png'
  if (avatar.startsWith('http')) return avatar
  return `http://127.0.0.1:8080${avatar}`
}

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')    
    if (token) {
      config.headers['token'] = JSON.parse(token)
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data

    const statusCode= Number(res.code)
    
    if (statusCode !== 200) {
      ElMessage({
        message: res.msg || '错误',
        type: 'error',
        duration: 5 * 1000
      })

      // if (statusCode === 401) {
      //   // token过期或未登录
      //   localStorage.removeItem('token')
      //   router.push('/login')
      // }
      
      return Promise.reject(new Error(res.msg || '错误'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error)
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service 